package com.lbn.monitor.app.history;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.free.framework.base.BaseFragmentPagerAdapter;
import com.lbn.monitor.R;
import com.lbn.monitor.api.model.Device;
import com.lbn.monitor.api.model.Pollutant;
import com.lbn.monitor.api.model.RealTimeValue;
import com.lbn.monitor.app.history.adapter.PollutantAdapter;
import com.lbn.monitor.app.history.adapter.TimeTypeAdapter;
import com.lbn.monitor.base.AppBaseActivity;
import com.lbn.monitor.util.Constant;
import com.lbn.monitor.util.DataUtils;
import com.lbn.monitor.widget.Appbar;
import com.lbn.monitor.widget.ListPopupWindow;
import com.lbn.monitor.widget.calendar.TimeUtils;
import com.lbn.monitor.widget.calendar2.CalendarPopupWindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import indi.free.widgets.custom_recycler_view.BaseRecyclerAdapter;

public class HistoryActivity extends AppBaseActivity<HistoryPresenter> implements
        IHistoryView<List<RealTimeValue>>, CalendarPopupWindow.OnChangedDate, BaseFragmentPagerAdapter.OnPageSelected{

    //    @BindView(R.id.recycler_view)
//    RecyclerView recyclerView;
//    @BindView(R.id.ptr_frame)
//    PtrFrameLayout ptrFrame;
    private static final String TYPE = "TYPE";
    @BindView(R.id.pollutant_content)
    TextView pollutantContent;
    @BindView(R.id.type_content)
    TextView typeContent;
    @BindView(R.id.search_start_time)
    TextView searchStartTime;
    @BindView(R.id.search_end_time)
    TextView searchEndTime;
    @BindView(R.id.activity_history)
    DrawerLayout activityHistory;
    @BindView(R.id.device_name)
    TextView deviceName;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.time_type)
    View timeType;
//    @BindView(R.id.pollutant)
//    Button pollutant;
//    @BindView(R.id.time_type)
//    Button timeType;
//    @BindView(R.id.time)
//    Button time;

//    private HistoryAdapter adapter;

    private String dataCn;
    private String startTime;
    private String endTime;
    private int page = 1;
    private String wuran;
    private int pollutantId;
    private String standardvalue;
    private String unit;
    private boolean isStartTime;

    private long nowDate;

    private String deviceMN;
    private final int DEVICE_LIST_REQ = 5000;

    private TableFragment tableFragment;
    private ChartFragment chartFragment;
    private BaseFragmentPagerAdapter pagerAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        ButterKnife.bind(this);
        setAppbar(new Appbar(this)
                .openBack()
                .setTitle("数据查询")
                .rightImageButton(R.drawable.search, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (activityHistory.isDrawerOpen(GravityCompat.END)) {
                            activityHistory.closeDrawer(GravityCompat.END);//关闭抽屉
                        } else {
                            activityHistory.openDrawer(GravityCompat.END);//打开抽屉
                        }
                    }
                }));
//                .rightButton("查询",
        nowDate = System.currentTimeMillis();
        this.startTime = TimeUtils.milliseconds2String(nowDate, TimeUtils.DEFAULT_NOT_HH);
        this.endTime = TimeUtils.milliseconds2String(nowDate, TimeUtils.DEFAULT_NOT_HH);
        searchStartTime.setText(startTime);
        searchEndTime.setText(endTime);
        timeTypeAdapter = new TimeTypeAdapter(this, DataUtils.getTimeType());
        pollutantAdapter = new PollutantAdapter(this, DataUtils.getPollutants(this));
        activityHistory.postDelayed(new Runnable() {
            @Override
            public void run() {
                activityHistory.openDrawer(GravityCompat.END);
            }
        }, 500);

        int type =  getIntent().getIntExtra(TYPE,0);

        if(type!=2){
            timeType.setEnabled(false);
            typeContent.setText(timeTypeAdapter.getItem(type).getName());
            dataCn = timeTypeAdapter.getItem(type).getValue();
        }else{
            typeContent.setText(timeTypeAdapter.getItem(1).getName());
            dataCn = timeTypeAdapter.getItem(1).getValue();
        }

        Pollutant item = pollutantAdapter.getItem(0);
        wuran = item.getPollutantsFactor();
        unit = item.getUnit();
        pollutantId = Integer.parseInt(item.getId());
    }

    @Override
    public void onBackPressed() {
        if (activityHistory.isDrawerOpen(GravityCompat.END)) {
            activityHistory.closeDrawer(GravityCompat.END);
            return;
        }
        super.onBackPressed();
    }

    public static void startActivity(Context context,int type) {
        Intent intent = new Intent(context, HistoryActivity.class);
        intent.putExtra(TYPE,type);
        context.startActivity(intent);
    }

    @Override
    protected HistoryPresenter createPresenter() {
        return new HistoryPresenter();
    }

    @Override
    protected void onPresenterCreated() {
        super.onPresenterCreated();
//        adapter = new HistoryAdapter(this, recyclerView, null);
//        adapter.setmOnLoadMoreListener(this);
////        adapter.setOnItemClickListener(this);
//        recyclerView.setAdapter(adapter);
//        initPtr(ptrFrame, this, false);
        tableFragment = TableFragment.newInstance();
        chartFragment = ChartFragment.newInstance();
        List<Fragment> fragments = new ArrayList<>();
        fragments.add(tableFragment);
        fragments.add(chartFragment);

        pagerAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(),fragments,viewPager,radioGroup);
        pagerAdapter .setOnPageSelected(this);
//        new FragmentTabAdapter(this, fragments, R.id.history_replace, radioGroup);

        onRefresh();
    }

//    @Override
//    public void onPtrRefresh() {
//        page = 1;
//        mPresenter.history(deviceMN, dataCn, startTime, endTime, page);
//    }


    public void onRefresh() {
        page = 1;
        mPresenter.history(deviceMN, dataCn, startTime, new String(endTime + " 23:59:59"), page);
        chartFragment.showLoadingView(true);
    }

    public void onLoadMore() {
        page++;
        mPresenter.history(deviceMN, dataCn, startTime, new String(endTime + " 23:59:59"), page);
        chartFragment.showLoadingView(true);
    }

    @Override
    public void refreshComplete(List<RealTimeValue> data) {
//        adapter.refreshData(data, !(data == null || data.size() < 20));
//        if (data == null || data.size() < 5) {
//            adapter.refreshData(data, false);
//        } else {
//            adapter.refreshData(data, true);
//        }
//        ptrFrame.refreshComplete();
        tableFragment.refreshComplete(data);
        chartFragment.refreshComplete(data);
    }

    @Override
    public void addMoreData(List<RealTimeValue> data, boolean isMore) {
//        adapter.addMoreData(data, isMore);
        tableFragment.addMoreData(data, isMore);
        chartFragment.addMoreData(data, isMore);
    }

    @OnClick({R.id.search_data, R.id.pollutant, R.id.time_type, R.id.time, R.id.time_end, R.id.device_list})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.pollutant:
                getPollutantPopup();
                break;
            case R.id.time_type:
                getTimeTypePopup();
                break;
            case R.id.time:
                isStartTime = true;
                getCalendarPopup();
//                startActivityForResult(new Intent(this, CalendarDialog.class), Constant.CALENDAR_REQUEST);
                break;
            case R.id.time_end:
                isStartTime = false;
                getCalendarPopup();
//                startActivityForResult(new Intent(this, CalendarDialog.class), Constant.CALENDAR_REQUEST);
                break;
            case R.id.device_list:
                DeviceListActivity.startActivity(this, DEVICE_LIST_REQ);
                break;
            case R.id.search_data:
                if (TextUtils.isEmpty(deviceMN)) {
                    showToast("请先选择设备");
                    return;
                }
                if (TextUtils.isEmpty(wuran)) {
                    wuran = pollutantAdapter.getItem(0).getPollutantsFactor();
                    pollutantId = Integer.parseInt(pollutantAdapter.getItem(0).getId());
                }
                if (TextUtils.isEmpty(dataCn)) {
                    dataCn = timeTypeAdapter.getItem(0).getValue();
                }
                if (!judgeTime()) {
                    return;
                }
                tableFragment.getAdapter().setPollutant(wuran);
                tableFragment.getAdapter().setPollutantId(pollutantId);
                List<Pollutant> pollutants = DataUtils.getPollutants(this);
                if (pollutants != null && pollutants.size() > 0) {
                    for (Pollutant p : pollutants) {
                        if (p.getPollutantsFactor().equals(wuran)) {
                            standardvalue = p.getStandardvalue();
                            tableFragment.getAdapter().setStandard(p.getStandardvalue());
                            break;
                        }
                    }
                }
                tableFragment.getPtrFrame().autoRefresh();
                activityHistory.closeDrawer(GravityCompat.END);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK)
            return;
        if (data != null) {

            switch (requestCode) {
                case DEVICE_LIST_REQ:
                    Device device = (Device) data.getSerializableExtra(Constant.DEVICE_DATA);
                    deviceMN = device.getDeviceMN();
                    deviceName.setText(device.getTreename());
                    chartFragment.setDevice(device.getTreename());
                    break;
                default:
            }
        }

//        switch (requestCode) {
//            case Constant.CALENDAR_REQUEST:
//                if (data != null) {
//                    long day = 86399;
//                    long endTime = data.getLongExtra(Constant.CALENDAR_END_TIME, 0) / 1000 + day;
//                    long startTime = data.getLongExtra(Constant.CALENDAR_START_TIME, 0) / 1000;
//
//                    this.startTime = TimeUtils.milliseconds2String(startTime * 1000, TimeUtils.DEFAULT_NOT_HH);
//                    this.endTime = TimeUtils.milliseconds2String(endTime * 1000, TimeUtils.DEFAULT_NOT_HH);
////                    time.setText("开始:"+ this.startTime+"\n结束:"+this.endTime);
//                    searchStartTime.setText(this.startTime);
//                    searchEndTime.setText(this.endTime);
//                }
//                break;
//        }
    }


//    @Override
//    public void onItemClick(View itemView, int pos) {
//        DeviceActivity.startActivity(this);
//    }


    private ListPopupWindow timeTypePopup;
    private TimeTypeAdapter timeTypeAdapter;

    private void getTimeTypePopup() {
        if (timeTypePopup == null) {
            timeTypePopup = new ListPopupWindow();
            timeTypePopup.onCreatePopup(this);
            timeTypeAdapter.setOnItemClickListener(getTimeTypeItemClickListener());
            timeTypePopup.setAdapter(timeTypeAdapter);
        }
        timeTypePopup.show(typeContent);
    }

    private ListPopupWindow pollutantPopup;
    private PollutantAdapter pollutantAdapter;

    public void getPollutantPopup() {
        if (pollutantPopup == null) {
            pollutantPopup = new ListPopupWindow();
            pollutantPopup.onCreatePopup(this);
            pollutantAdapter.setOnItemClickListener(getPollutantItemClickListener());
            pollutantPopup.setAdapter(pollutantAdapter);
        }
        pollutantPopup.show(pollutantContent);
    }

    private CalendarPopupWindow calendarPopup;

    public void getCalendarPopup() {
        if (calendarPopup == null) {
            calendarPopup = new CalendarPopupWindow();
            calendarPopup.createPopup(this);
            calendarPopup.setOnChangedDate(this);
        }
        calendarPopup.show(activityHistory);
    }


    private BaseRecyclerAdapter.OnItemClickListener getTimeTypeItemClickListener() {
        return new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
//                timeType.setText(timeTypeAdapter.getItem(pos).getName());
                typeContent.setText(timeTypeAdapter.getItem(pos).getName());
                dataCn = timeTypeAdapter.getItem(pos).getValue();

//                if(pagerAdapter.getPosition()==1){
//                    ((Appbar)mFjrAppbar).setTitle(wuran+"-"+timeTypeAdapter.getItem(pos).getName());
//                }

                timeTypePopup.dismiss();
            }
        };
    }

    private BaseRecyclerAdapter.OnItemClickListener getPollutantItemClickListener() {
        return new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View itemView, int pos) {
//                pollutant.setText(pollutantAdapter.getItem(pos));
                Pollutant item = pollutantAdapter.getItem(pos);
                wuran = item.getPollutantsFactor();
                unit = item.getUnit();
                pollutantId = Integer.parseInt(item.getId());

                pollutantContent.setText(wuran);

                pollutantPopup.dismiss();
            }
        };
    }

    @Override
    public void onChangedDate(String date) {
        if (isStartTime) {
            startTime = date;
            searchStartTime.setText(date);
        } else {
            endTime = date;
            searchEndTime.setText(date);
        }
    }

    private static final String TAG = "神兽草泥马";

    public boolean judgeTime() {

//        Log.e(TAG, "startTime = " + startTime);
//        Log.e(TAG, "endTime = " + endTime);
//        Log.e(TAG, "nowDate = " + TimeUtils.milliseconds2String(nowDate, TimeUtils.DEFAULT_NOT_HH));

        long start = TimeUtils.string2Time(startTime);
        long end = TimeUtils.string2Time(endTime);

//        Log.e(TAG, "start = " + start);
//        Log.e(TAG, "end = " + end);
//        Log.e(TAG, "nowDate = " + nowDate);


        if (nowDate < start || nowDate < end) {
            showToast("不可查询超过当前时间" + TimeUtils.milliseconds2String(nowDate, TimeUtils.DEFAULT_NOT_HH) + "的数据");
            return false;
        }

        if (TimeUtils.isSameDate(start, end)) {
            showToast("不可跨月查询");
            return false;
        }

        long t = end - start;

        if (t < 0) {
            showToast("结束时间不能小于开始时间");
            return false;
        }


        if (dataCn.equals("2051")) {
            if (t > 172800000) {
                showToast("分钟查询时间不可超过3天");
                return false;
            }
        }
        return true;
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        if(tableFragment==null){
            return;
        }
        tableFragment.getPtrFrame().refreshComplete();
        if(pagerAdapter.getPosition()==1){
            ((Appbar)mFjrAppbar).setTitle(wuran+"-"+typeContent.getText().toString());
        }
    }

    public int getPollutantId() {
        return pollutantId;
    }

    public String getStandardvalue() {
        return standardvalue;
    }


    @Override
    public void onPageSelected(int position) {
        String title = "";
        switch (position){
            case 0:
                title = "数据列表";
                break;
            case 1:
                title = wuran+"-"+typeContent.getText().toString();
                break;
        }
        ((Appbar)mFjrAppbar).setTitle(title);
    }

    public String getWuran() {
        return wuran;
    }

    public String getUnit() {
        return unit;
    }
}
